package com.cci.kangdao.service.impl;

import com.cci.kangdao.azureAD.AzureADTool;
import com.cci.kangdao.dao.LoginDao;
import com.cci.kangdao.dao.UserTokenTMapper;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dao.model.UserTokenT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.AzureTokenService;
import com.cci.kangdao.service.MobileSmsService;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.service.SendSMSLogService;
import com.cci.kangdao.utilTool.*;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 米艳春
 * @version 1.0
 * @Description: 登录页
 * @Company: cty
 * @date 2018-01-17
 */
@Service("mobileSmsService")
public class MobileSmsServiceImpl implements MobileSmsService {
    private Logger log = Logger.getLogger(this.getClass().getName());

    @Resource
    private PropertiesUtils propertiesUtils;
    @Autowired
    private RedisClientUtils redisClientUtils;
    @Autowired
    private SendSMSLogService sendSMSLogService;
    @Resource
    private LoginDao loginDao;
    @Resource
    private UserTokenTMapper userTokenTMapper;
    @Resource
    private AzureTokenService azureTokenService;
    @Resource
    private MobileSmsService mobileSmsService;

    private Pattern WWID_PATTERN = Pattern.compile("^([A-Za-z]{2})([0-9A-Za-z]{3})$");

    private static final String SUBJECT = "e路康明斯验证码信息";

    private static final String CONTENT = "尊敬的用户，您好！  e路康明斯验证码为：%s，5分钟有效，谢谢！";
    Pattern p = Pattern.compile("^1[3456789]\\d{9}$");
    /**
     * App获取短信接口
     *
     * @param map
     * @return
     */
    @Override
    public ModelAndView getMobileSms(Map map) {

        HttpServletResponse response = (HttpServletResponse) map.get("response");
        HttpServletRequest request = RequestContextHolder.getRequest();
        JSONObject obj = new JSONObject();

        /**
         * 1、验证手机号是否为空
         */
        if (map.get("mobile") == null || map.get("mobile").toString().equals("")) {
            obj.put("status", -5);
            obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));
            sendSMSLogService.insertSendSMSLog(0, map.get("type") + "", "", "", "-5");
            //返回客户
            ParameterTool.writeResponse(response, obj.toString());
            obj = null;
            return null;
        }
        String mobile = map.get("mobile").toString();
        mobile = AESTool.decryptString(mobile); //解密

        Matcher matcher = p.matcher(mobile);
        if (!matcher.matches()) {
            ParameterTool.writeErrorResponse(response, -47);
            return null;
        }
        // 加锁处理，避免发生多次提交。
        String lockKey= "getMobileSms-" + mobile ;
        if (!redisClientUtils.lock(lockKey, 60L)) {
            //防止并发
            ParameterTool.writeErrorResponse(response, -48);
            return null;
        }
        String type = (String) map.get("type");
        try {
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            request.getSession(true);
            /**
             * 2、Type：0注册App获取验证码，1是密码找回，2是手机快捷登录，3是修改密码，4是登录初始化，5是申请权限
             * 2.1 Type：0注册App获取验证码
             */
            if (StringUtils.isEmpty(type) || type.equals("0")) {
                // 注册APP验证码
                // 查询用户能否注册App
                String headerType = request.getHeader("type");
                if (StringUtils.isEmpty(headerType)) {
                    headerType = "0";
                }
                if (StringUtils.isNotEmpty(headerType) && !"1".equals(headerType)) {
                    UserT userT = loginDao.getUserByUserName(mobile);
                    if (userT != null) {
                        //返回客户
                        obj.put("status", -4);
                        obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-4));
                        sendSMSLogService.insertSendSMSLog(0, map.get("type") + "", "", "", "-4");
                        ParameterTool.writeResponse(response, obj.toString());
                        obj = null;
                        return null;
                    }
                    List<UserT> userList = loginDao.getUserByPhone(mobile);
                    if (!CollectionUtils.isEmpty(userList)) {
                        //返回客户
                        obj.put("status", -4);
                        obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-4));

                        sendSMSLogService.insertSendSMSLog(0, map.get("type") + "", "", "", "-4");
                        ParameterTool.writeResponse(response, obj.toString());
                        obj = null;
                        return null;
                    }
                }
                /**
                 * 生成验证吗
                 */
                String smsCode = PublicTool.getFourRandom();
                log.info("您的验证码是" + smsCode);
                redisClientUtils.set("sms" + mobile, smsCode, 90); //1分钟有效,但是实际是时间太短
                /**
                 * 发送短信
                 */
                String smstext = "您此次的验证码为{验证码}，有效期1分钟，请输入后进行验证，谢谢！";
                String reuslt = SmsUtils.sendMessageNotTD(mobile, smstext.replace("{验证码}", smsCode));

                sendSMSLogService.insertSendSMSLog(1, map.get("type") + "", mobile, smstext.replace("{验证码}", smsCode), reuslt);

                //返回客户
                obj.put("status", 0);
                obj.put("msg", "");
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            } else if (type.equals("1")) {
                // 忘记密码，进行密码找回
                List<UserT> userList = loginDao.getUserByPhone(mobile);
                if (CollectionUtils.isEmpty(userList)) {
                    // 返回客户
                    sendSMSLogService.insertSendSMSLog(1, map.get("type") + "", "", "", "-3");
                    ParameterTool.writeErrorResponse(response,-3);
                    return null;
                } else if (userList.size() > 1) {
                    //返回客户
                    sendSMSLogService.insertSendSMSLog(1, map.get("type") + "", "", "", "-10");
                    ParameterTool.writeErrorResponse(response,-10);
                    return null;
                }
                UserT userT = userList.get(0);
                if(WWID_PATTERN.matcher(userT.getUserName()).matches()){
                    ParameterTool.writeResponse(response,1,"您为康明斯内部用户，暂不支持修改密码");
                    return null;
                }

                // 生成验证码
                String smsCode = PublicTool.getFourRandom();
                log.info("您的验证码是" + smsCode);
                redisClientUtils.set("sms" + mobile, smsCode, 90); //1分钟有效,但是实际是时间太短
                //发送短信
                String smstext = "您此次的验证码为{验证码}，有效期1分钟，请输入后进行验证，谢谢！";
                String reuslt = SmsUtils.sendMessageNotTD(mobile, smstext.replace("{验证码}", smsCode));
                //存储发送记录
                sendSMSLogService.insertSendSMSLog(1, map.get("type") + "", mobile, smstext.replace("{验证码}", smsCode), reuslt);
                //返回客户
                //Map<String,Object> responseDataMap = new HashMap<>();
                //responseDataMap.put("userId",String.valueOf(userT.getId()));
                ParameterTool.writeSuccessResponse(response);
            } else if (type.equals("2")) {
                // 手机快捷登录
                //todo 确定后期是否还存在
                /**
                 * 2.3、手机快捷登录操作，查询用户是否存在
                 */
                UserT userT = loginDao.getUserByUserName(mobile);
                if (userT == null) {
                    /**
                     * 如果用户不存在，新建用户
                     */
                    String AUTHORITY = this.propertiesUtils.getPropertiesValue("authority");
                    String RESOURCE = this.propertiesUtils.getPropertiesValue("resource");
                    String webClient_id = this.propertiesUtils.getPropertiesValue("webClient_id");
                    String webClientSecret = this.propertiesUtils.getPropertiesValue("webClientSecret");
                    String tenant = this.propertiesUtils.getPropertiesValue("tenant");
                    AUTHORITY = AUTHORITY.replace("common", tenant);
                    /**
                     * 3.1、Azure Ad获取token
                     */
                    IAuthenticationResult result = AzureADTool.getAccessTokenByClient(webClient_id, webClientSecret, AUTHORITY, RESOURCE);
                    if (result == null) {
                        obj.put("status", -99);
                        obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));

                        sendSMSLogService.insertSendSMSLog(0, map.get("type") + "", "", "", "-99");
                        //返回客户
                        ParameterTool.writeResponse(response, obj.toString());
                        obj = null;
                        return null;
                    }
                    /**
                     * 3.2、Azure AD使用token去新建用户
                     */
                    String pwd = "Test1234";
                    String userJson = AzureADTool.createAzureUser(mobile, pwd, result.accessToken(), tenant);
                    /**
                     * 3.3、保存用户数据到数据库
                     */
                    JSONObject jsonObj = new JSONObject(userJson);
                    UserT bean = new UserT();
                    bean.setAduserId(jsonObj.getString("objectId"));
                    bean.setUserName(mobile);
                    bean.setAzureToken(result.accessToken());
                    int flag = loginDao.insertUser(bean);
                    if (flag <= 0) {
                        obj.put("status", -99);
                        obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-99));

                        sendSMSLogService.insertSendSMSLog(0, map.get("type") + "", "", "", "-99");
                        //返回客户
                        ParameterTool.writeResponse(response, obj.toString());
                        return null;
                    }
                }
                /**
                 * 生成验证吗
                 */
                String smsCode = PublicTool.getFourRandom();
                log.info("您的验证码是" + smsCode);
                redisClientUtils.set("sms" + mobile, smsCode, 90); //1分钟有效,但是实际是时间太短
                /**
                 * 发送短信
                 */
                String smstext = "您此次的验证码为{验证码}，有效期1分钟，请输入后进行验证，谢谢！";
                String reuslt = SmsUtils.sendMessageNotTD(mobile, smstext.replace("{验证码}", smsCode));

                sendSMSLogService.insertSendSMSLog(1, map.get("type") + "", mobile, smstext.replace("{验证码}", smsCode), reuslt);

                //返回客户
                obj.put("status", 0);
                obj.put("msg", "");
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
            } else if(type.equals("3")){
                // 修改密码
                /**
                 * 2.4、根据手机号查询用户是否存在
                 */
                List<UserT> userList = loginDao.getUserByPhone(mobile);
                if (userList == null || userList.size() == 0) {
                    //返回客户
                    obj.put("status", -3);
                    obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-3));
                    sendSMSLogService.insertSendSMSLog(0, map.get("type") + "", "", "", "-3");
                    ParameterTool.writeResponse(response, obj.toString());
                    obj = null;
                    return null;
                }
                /**
                 * 生成验证吗
                 */
                String smsCode = PublicTool.getFourRandom();
                log.info("您的验证码是" + smsCode);
                redisClientUtils.set("sms" + mobile, smsCode, 90); //1分钟有效,但是实际是时间太短
                /**
                 * 发送短信
                 */
                String smstext = "您此次的验证码为{验证码}，有效期1分钟，请输入后进行验证，谢谢！";

                String reuslt = SmsUtils.sendMessageNotTD(mobile, smstext.replace("{验证码}", smsCode));

                sendSMSLogService.insertSendSMSLog(1, map.get("type") + "", mobile, smstext.replace("{验证码}", smsCode), reuslt);
                //返回客户
                obj.put("status", 0);
                obj.put("msg", "");
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
            }else if(type.equals("4")){
                // 初始化用户信息
                // 获取该手机是否已注册
                List<UserT> userList = loginDao.getUserByPhone(mobile);
                if (!CollectionUtils.isEmpty(userList)) {
                    ParameterTool.writeErrorResponse(response,-4);
                    return null;
                }
                // 发送短信验证码
                generateSmsCode(mobile,type);
                ParameterTool.writeSuccessResponse(response);
            }else if(type.equals("5")){
                // 权限申请
                List<UserT> userList = loginDao.getUserByPhone(mobile);
                if(CollectionUtils.isEmpty(userList)){
                    ParameterTool.writeErrorResponse(response,-3);
                    return null;
                }
                // 发送短信验证码
                generateSmsCode(mobile,type);
                ParameterTool.writeSuccessResponse(response);
            }else {
                log.error("发送短信验证码，异常的type类型：" + type);
                ParameterTool.writeErrorResponse(response,-10);
                return null;
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return null;
    }
    private void generateSmsCode(String mobile,String type){
        //随机生成验证码
        String smsCode = PublicTool.getFourRandom();
        log.info("您的验证码是" + smsCode);
        //1分钟有效,但是实际是时间太短
        redisClientUtils.set("sms" + mobile, smsCode, 90);
        //拼装短信内容
        String smstext = "您此次的验证码为{验证码}，有效期1分钟，请输入后进行验证，谢谢！";
        // 发送验证码
        String reuslt = SmsUtils.sendMessageNotTD(mobile, smstext.replace("{验证码}", smsCode));
        sendSMSLogService.insertSendSMSLog(1, type, mobile, smstext.replace("{验证码}", smsCode), reuslt);
    }

    //短信验证码次数加一
    @Override
    public int smsCodeTimes(String mobile, int timeMax) {
        return smsCodeTimes(mobile, timeMax, true, "");
    }

    public int smsCodeTimes(String mobile, int timeMax, boolean flag, String type) {
        String key = "";
        if (StringUtils.isNotBlank(type)) {
            key = "smsTimes" + "-" + type + "-" + mobile;
        } else {
            key = "smsTimes" + mobile;
        }

        String times = (String) redisClientUtils.get(key);
        int timeInt = 0;
        if (StringUtils.isNotBlank(times)) {
            timeInt = Integer.valueOf(times);
        }
        int timesV = timeInt + 1;
        int seconds = flag ? 300 : 0;
        if (timesV <= timeMax) {
            redisClientUtils.set(key, String.valueOf(timesV), 300);
        }
        return timesV;
    }


    /**
     * App验证手机号接口
     *
     * @param map
     * @return
     */
    @Override
    public ModelAndView verifyMobile(Map map) {
        try {
            HttpServletResponse response = (HttpServletResponse) map.get("response");
            JSONObject obj = new JSONObject();
            /**
             * 1、验证手机号、短信验证码是否为空
             */
            if (map.get("mobile") == null || map.get("mobile").toString().equals("")) {
                obj.put("status", -5);
                obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }
            if (map.get("smsCode") == null || map.get("smsCode").toString().equals("")) {
                obj.put("status", -5);
                obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(-5));

                //返回客户
                ParameterTool.writeResponse(response, obj.toString());
                obj = null;
                return null;
            }

            String mobile = map.get("mobile").toString();
            if (!(map.containsKey("isEncrypt") && MapUtils.getInteger(map, "isEncrypt") == 1)) {
                mobile = AESTool.decryptString(mobile);
            }
            Object typeLock = redisClientUtils.getObject("sms-lock-" + MapUtils.getString(map, "type", "")
                    + "-" + mobile);
            if (null != typeLock) {
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(typeLock.toString());
                Integer locktimeRedis = jsonObject.getInteger("locktime");
                String currentDate = jsonObject.getString("currentDate");
                boolean before = LocalTimeUtil.isBefore(LocalTimeUtil.getTimeAfterSeconds(currentDate, locktimeRedis * 60), LocalTimeUtil.getRealCurrentTime());
                if (!before) {
                    redisClientUtils.delkey("sms" + mobile);
                    ParameterTool.writeErrorResponse(response, -55, "您已连续输错多次，请" + LocalTimeUtil.turnDayHourMinuteString((int) locktimeRedis) + "后再试！");
                    return null;
                }
            }

            /**
             * 2、redis里面获取用户的验证
             */
            String redisCode = redisClientUtils.get("sms" + mobile);
            log.info(redisCode);
            if (redisCode == null || redisCode.equals("") || !map.get("smsCode").toString().trim().equals(redisCode)) {
                int timeMax = 5;
                int times = this.smsCodeTimes(mobile, timeMax, false, MapUtils.getString(map, "type", ""));
                if (times >= timeMax) {
                    //添加  输错6次后，5min后在重试，从第7次开始等待时间翻倍，直至输入成功后，恢复正常时间。
                    int locktime = 5;
                    Map<String, Object> lockMap = new HashMap<>();
                    Object type = redisClientUtils.getObject("sms-lock-" + MapUtils.getString(map, "type", "")
                            + "-" + mobile);
                    if (null != type) {
                        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(type.toString());
                        Integer locktimeRedis = jsonObject.getInteger("locktime");
                        locktime = 2 * locktimeRedis;
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("locktime", locktime);
                    jsonObject.put("currentDate", LocalTimeUtil.getRealCurrentTime());
                    redisClientUtils.setObject("sms-lock-" + MapUtils.getString(map, "type", "") + "-" + mobile, jsonObject, 0);
                    redisClientUtils.delkey("sms" + mobile);
                    if (times == 5) {
                        ParameterTool.writeErrorResponse(response, -55);
                        return null;
                    } else {
                        ParameterTool.writeErrorResponse(response, -55, "您已连续输错多次，请" + LocalTimeUtil.turnDayHourMinuteString(locktime) + "后再试！");
                        return null;
                    }
                }
                ParameterTool.writeErrorResponse(response, -6);
                return null;
            } else {
                redisClientUtils.delkey("sms-lock-" + MapUtils.getString(map, "type", "") + "-" + mobile);
                redisClientUtils.delkey("smsTimes" + "-" + MapUtils.getString(map, "type", "") + "-" + mobile);
                redisClientUtils.delkey("sms" + mobile);
            }

            /**
             * 3、Type：0注册，1是密码找回，2是手机快捷登录，3是修改密码
             * 3.1、type为0返回验证成功
             */
            if (map.get("type") == null || map.get("type").toString().equalsIgnoreCase("0") || map.get("type").toString().equalsIgnoreCase("3")) {
                //删除加时间的key
                redisClientUtils.delkey("sms-lock-" + MapUtils.getString(map, "type", "") + "-" + mobile);
                ParameterTool.writeSuccessResponse(response);
                return null;
            } else {
                if(map.get("type").toString().equalsIgnoreCase("1")){
                    UserT userT = loginDao.getUserByUserName(mobile);
                    if (userT == null) {
                        List<UserT> list = loginDao.getUserByPhone(mobile);
                        if (CollectionUtils.isNotEmpty(list)) {
                            userT = list.get(0);
                        } else {
                            //删除加时间的key
                            redisClientUtils.delkey("sms-lock-" + MapUtils.getString(map, "type", "") + "-" + mobile);
                            ParameterTool.writeErrorResponse(response, -3);
                            return null;
                        }
                    }
                    Map<String, Object> responseDataMap = new HashMap<>();
                    responseDataMap.put("userId", String.valueOf(userT.getId()));
                    //删除加时间的key
                    redisClientUtils.delkey("sms-lock-" + MapUtils.getString(map, "type", "") + "-" + mobile);
                    ParameterTool.writeSuccessResponse(response, responseDataMap);
                }else{
                    // 当状态为2时，返回userid+token
                    UserT userT = loginDao.getUserByUserName(mobile);
                    if (userT == null) {
                        List<UserT> list = loginDao.getUserByPhone(mobile);
                        if (null != list && list.size() == 1) {
                            userT = list.get(0);
                        } else {
                            //删除加时间的key
                            redisClientUtils.delkey("sms-lock-" + MapUtils.getString(map, "type", "") + "-" + mobile);
                            ParameterTool.writeErrorResponse(response, -3);
                            return null;
                        }
                    }
                    obj.put("status", 0);
                    obj.put("msg", "");
                    obj.put("userid", userT.getId());

                    UserTokenT userTokenT = userTokenTMapper.selectByUserId(userT.getId());
                    if (null != userTokenT) {
                        String token = null;
                        if (LocalTimeUtil.isBefore(LocalTimeUtil.getRealCurrentTime(), userTokenT.getExpireTime())) {
                            token = userTokenT.getAccessToken();
                        } else {
                            token = azureTokenService.refreshToken(String.valueOf(userT.getId()));
                        }
                        obj.put("token", token);
                    } else {
                        ParameterTool.writeErrorResponse(response);
                    }
                    //删除加时间的key
                    redisClientUtils.delkey("sms-lock-" + MapUtils.getString(map, "type", "") + "-" + mobile);
                    //返回客户
                    ParameterTool.writeResponse(response, obj.toString());
                    obj = null;
                }
            }

        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        return null;
    }


    @Override
	public ModelAndView getCodeByEmail(Map<String, Object> map) throws UnsupportedEncodingException, MessagingException {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		String email = MapUtils.getString(map, "email");
		// 应用场景：1，修改密码；2，忘记密码；3，绑定邮箱；4，解绑邮箱
		int type = MapUtils.getIntValue(map, "type");

		if(StringUtils.isBlank(email) || 0 == type) {
			//返回客户
            ParameterTool.writeResponse(response, -5, ApiErrorCode.getInstance().getErrorMsg(-5));
            return null;
		}

		// 验证邮箱是否可用
		int count = loginDao.getUserCountByEmail(email);
		if(type == 2 || type == 4) {
			if(count == 0) {
				ParameterTool.writeResponse(response, -31, ApiErrorCode.getInstance().getErrorMsg(-31));
	            return null;
			}
		}

		if(type == 3 && count > 0) {
			ParameterTool.writeResponse(response, -30, ApiErrorCode.getInstance().getErrorMsg(-30));
            return null;
		}
        // 加锁处理，避免发生多次提交。
        String lockKey= "getCodeByEmail-" + email ;
        if (!redisClientUtils.lock(lockKey, 300L)) {
            //防止并发
            ParameterTool.writeErrorResponse(response, -48);
            return null;
        }
		//生成验证码
		String code = PublicTool.getFourRandom();

		//发送验证码
		MailUtil.sendMail(email, SUBJECT, String.format(CONTENT, code));
		redisClientUtils.set("email" + email, code, 300);

		ParameterTool.writeSuccessResponse(response);
		return null;
	}

	@Override
	public ModelAndView verifyEmailCode(Map<String, Object> map) {
		HttpServletResponse response = (HttpServletResponse) map.get("response");
		String email = MapUtils.getString(map, "email");
		// 应用场景：1，修改密码；2，忘记密码；3，绑定邮箱；4，解绑邮箱
		int type = MapUtils.getIntValue(map, "type");
		String code = MapUtils.getString(map, "code").trim();
		Long userId = MapUtils.getLong(map, "userId");

		if(StringUtils.isBlank(email) || 0 == type || StringUtils.isBlank(code)) {
			//返回客户
            ParameterTool.writeResponse(response, -5, ApiErrorCode.getInstance().getErrorMsg(-5));
            return null;
		}

		if(type == 3 || type == 4) {
			if(null == userId) {
				ParameterTool.writeResponse(response, -5, ApiErrorCode.getInstance().getErrorMsg(-5));
	            return null;
			}
		}

		// 验证验证码是否正确
		String redisCode = redisClientUtils.get("email" + email);

        if (redisCode == null || redisCode.equals("") || !code.equals(redisCode)) {
            int timeMax = 5;
            int times = mobileSmsService.smsCodeTimes(email,timeMax);
            if(times >= timeMax){
                redisClientUtils.delkey("email" + email);
                ParameterTool.writeErrorResponse(response,-55);
                return null;
            }
            ParameterTool.writeErrorResponse(response, -6);
            return null;
        }

		// 根据应用场景进行逻辑处理
        if(type == 3) { //绑定邮箱
			loginDao.setEmail(userId, email);

			//修改缓存中的数据
			resetUserInfo(userId, email);

		} else if(type == 4) { //解绑邮箱
			loginDao.blankEmail(userId);

			//修改缓存中的数据
			resetUserInfo(userId, "");
		} else {
			if(type == 1) { //修改密码
				ParameterTool.writeSuccessResponse(response);
				return null;
			} else if(type == 2) { //忘记密码
				UserT user = loginDao.getUserByEmail(email);
                if (user == null) {
                    ParameterTool.writeErrorResponse(response, -21);
                    return null;
                }
                Map<String,Object> responseDataMap = new HashMap<>();
                responseDataMap.put("userId", user.getId());
                responseDataMap.put("userName", user.getUserName());
                ParameterTool.writeSuccessResponse(response,responseDataMap);
                return null;
			} else {
				ParameterTool.writeErrorResponse(response, -99);
				return null;
			}
		}

        ParameterTool.writeSuccessResponse(response);
		return null;
	}

	public void resetUserInfo(Long userId, String email) {
		UserT userT = (UserT) redisClientUtils.getObject("userT" + userId);
        if (userT != null) {
        	userT.setEmail(email);
            int redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
            redisClientUtils.setObject("userT" + userId, userT, redisCacheTime);
        }
	}

}
